package com.imooc.luckymoney.aspect;

import com.imooc.luckymoney.entity.Log;
import com.imooc.luckymoney.repository.LogRepository;
import com.imooc.luckymoney.repository.LuckymoneyRepository;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Aspect
@Component
public class HttpAspect {
    private static final Logger logger = LoggerFactory.getLogger(HttpAspect.class);

    @Autowired
    private LogRepository repository;

    Log log;

    @Pointcut("execution(public * com.imooc.luckymoney.controller.LuckymoneyController.*(..))")
    public void logPointcut(){

    }

    @Before("logPointcut()")
    public void Before(JoinPoint joinPoint){
        log = new Log();
        ServletRequestAttributes  attributes= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //url
        logger.info("url={}",request.getRequestURL());
        log.setUrl(request.getRequestURL().toString());
        //method
        logger.info("method={}",request.getMethod());
        log.setMethod(request.getMethod());
        //ip
        logger.info("ip={}",request.getRemoteAddr());
        log.setIp(request.getRemoteAddr());
        //class
        StringBuffer sbf = new StringBuffer();
        sbf.append("class_method=");
        sbf.append(joinPoint.getSignature().getDeclaringTypeName());
        sbf.append(".");
        sbf.append(joinPoint.getSignature().getName());
        String s = sbf.toString();
        logger.info("class_method={}",joinPoint.getSignature().getName());
        log.setClassMethod(s);
    }

    @After("logPointcut()")
    public void After(){
        repository.save(log);
        logger.info("log is success save");
    }

    @AfterReturning(pointcut = "logPointcut()",returning = "object")
    public void afterReturning(Object object){
        logger.info("return={}",object);
    }
}
